define(
	[
		'require',
		'../../business/ctrls/detail_ctrl',
		'../../business/ctrls/center_ctrl'
	],
	function(require){
			Controller = Ember.Controller.extend({
			// 告警台监听查询功能
			alarmTypeChange: Ember.observer("form.alarmType",function(){
				this.queryAlarm();
			}),
			// alarmSourceChange: Ember.observer("form.source",function(){
			// 	this.queryAlarm();
			// }),
			// alarmKeyChange: Ember.observer("form.key",function(){
			// 	this.queryAlarm();
			// }),
			alarmClearStatusChange: Ember.observer("form.clearStatus",function(){
				this.queryAlarm();
			}),
			alarmStatusChange: Ember.observer("form.status",function(){
				this.queryAlarm();
			}),

			init : function() {
				this._super();
			},

			clearStatuss :  Ember.A([
				{
					name: "全部",
					code:-1,
				},
				{
					name: "新告警",
					code:0,
				},
				{
					name: "已恢复",
					code:1,
				}
			]),
			initTime: function(){
		        var ctrl = this;

		        var sdate = new Date(new Date(new Date() - timeD_value)-1000*60*60*24*7 - 60000);
		        sdate.setSeconds(0);
		        sdate.setMilliseconds(0); 

		        ctrl.set("startDate",new Date(+sdate));

		        var edate = new Date(new Date() - timeD_value - 60000);
		        edate.setSeconds(0);
		        edate.setMilliseconds(0); 
		        //console.log(new Date(+edate));

		        ctrl.set("endDate",new Date(+edate));
		        console.log(ctrl.get("startDate"));
		    },
			// startDate:Ember.computed(function(){
			// 	//var date = new Date(new Date() - timeD_value - 3600000*24*7-60000);
			// 	var date = new Date(new Date(new Date() - timeD_value)-1000*60*60*24*7);
			// 	return new Date(+date);

			// }),

			// endDate:Ember.computed(function(){
			// 	//var date = new Date(new Date() - timeD_value - 60000);
			// 	var date = new Date(new Date() - timeD_value);
			// 	return new Date(+date);
			// }),
			keyUpEvent: function(){
				var ctrl = this;
				setTimeout(function(){
					$(".mouseKeyUp").on("keyup",function(event){
						if(event.keyCode == 13){
							ctrl.queryAlarm();
						}
					})
				})
			},

			form : {
				severity:50,
				firstTime : new Date(new Date(new Date() - timeD_value)-1000*60*60*24*7),
				lastTime : new Date(new Date() - timeD_value),
				alarmType : null,
				source : "",
				status : -1,
				clearStatus: 0,
				key : "",
				alarmNum1:0,
				alarmNum2:0,
				alarmNum3:0
			},

			initConfData: function(){
				var ctrl = this;
				var form = this.get("form");
				ctrl.set("sortField",null);
				ctrl.set("isAlarmMenu1",false);
				ctrl.set("isAlarmMenu2",true);
				ctrl.set("isAlarmMenu3",true);
				ctrl.set("form.clearStatus", 0); // 默认显示 新告警 参数
				this.store.ajax("GET", "alarms/alarmsRankNum").then(function(response) {
					//todo: 保存成功逻辑
					var rankList=response.serRankNums;
					if(rankList){
						for(var k=0;k<rankList.length;k++){
							rankObj=rankList[k];
							if(rankObj.alarmCode==50){
								if(rankObj.alarmNum>99){
									ctrl.set("form.alarmNum1","99+");
								}else{
									ctrl.set("form.alarmNum1",rankObj.alarmNum);
								}
							}
							if(rankObj.alarmCode==20){
								if(rankObj.alarmNum>99){
									ctrl.set("form.alarmNum2","99+");
								}else{
									ctrl.set("form.alarmNum2",rankObj.alarmNum);
								}
							}
							if(rankObj.alarmCode==10){
								if(rankObj.alarmNum>99){
									ctrl.set("form.alarmNum3","99+");
								}else{
									ctrl.set("form.alarmNum3",rankObj.alarmNum);
								}
							}
						}
						ctrl.set('menuLists',Ember.A(rankList));
					}
				});
				
				this.store.ajax("GET", "configs/systemConfig",{
					configItem:"alert"
				}).then(function(response) {
					//todo: 保存成功逻辑
					var statusList=response.configData.alert_status;
					var typeList=response.configData.alert_type;
					if(typeList){
						var ta = JSON.parse(typeList);
						for(var i = ta.length - 1; i >= 0; i--) {
						    if(ta[i].code === 'lrpm') {
						       ta.splice(i, 1);
						    }
						    if(ta[i].code === 'blrpm') {
						       ta.splice(i, 1);
						    }
						}
						ctrl.set('types',Ember.A(ta));
					}
					if(statusList){
						console.log(Ember.A(JSON.parse(statusList)));
						ctrl.set('statuss',Ember.A(JSON.parse(statusList)));
					}
					//重新设置默认值
					ctrl.set('form.alarmType',null);
					ctrl.set('form.severity',50);
					ctrl.set("pageIndex", 0);
					ctrl.set('form.status',-1);
				});
				
				
				ctrl.requireAlarmsData();
				//ctrl.queryAlarm();
			},

			//列表数据查询
			requireAlarmsData:function(){
			
				var ctrl = this;
				var form = ctrl.get("form");
					console.log(form.status +'1');
					console.log(form.clearStatus);
				var sortField = ctrl.get("sortField");
				var sortBy = ctrl.get("sortBy");
				var pageIndex = ctrl.get("pageIndex");
				var param = {
					severity:form.severity,
					firstTime : +ctrl.get("startDate"),
					lastTime : +ctrl.get("endDate"),
					type : form.alarmType,
					source : form.source,
					status : form.status,
					clearStatus :form.clearStatus,
					pageIndex:pageIndex,
					sortField:sortField,
					sortBy:sortBy,
					pageSize: 10,
					key : form.key
				};
				if (isLocalDebugModel) {
					param.firstTime = 1436400000000;
					param.lastTime = 1437091199000;
				}
				return ctrl.store.ajax("GET", "alarms/alarmsData", param)
				.then(function(response) {
					//todo: 保存成功逻辑
					if(response.meta){
						ctrl.set("pageIndex",response.meta.pageIndex);
						ctrl.set("pageSize",response.meta.pageSize);
						ctrl.set("totalRows",response.meta.total);
						if(response.result){
							ctrl.set('gridDataSource',response.result);
						}
					}

					// 设置当前radio按钮选中
					$("input[name='alarm-type']").each(function(index){
						index++;
						if(!ctrl.get("isAlarmMenu"+index)){
							$(this).prop("checked",true);
							return false;
						}
					})
					
				});
			},
			
			//菜单栏级别及统计数存放查询
			menuLists:  Ember.A(),

			//告警类型列表
			types:  Ember.computed(function(key, value){
				if(arguments.length == 1){
					return Ember.A();
				}else{
					value.splice(0, 0,{
						"name":"全部",
						"code":null,
					});
					return value;
				}
			}),

			//告警确认类型列表
			statuss:  Ember.computed(function(key, value){
				if(arguments.length == 1){
					return Ember.A();
				}else{
					value.splice(0, 0,{
						"name":"全部",
						"code":-1,
					});
					return value;
				}
			}),
			
			gridColumns: [
				{
					headerText: "",
					dataKey:"id",
					width: 45,
					allowSort: false,
					selectAll: true,
					ensurePxWidth: true,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data;
							var cb = $("<input type='checkbox' class='grid-checkbox'/>");

							cb.prop("checked", data._checked)
								.appendTo(args.$container)
								.data("model", data);
				
							data._$checkbox = cb;
							data.ctrl = ctrl;
							args.$container
								.on("click", ":checkbox", ctrl.networkCheckboxClick);
							//将数据的_checked属性与checkbox的选中状态绑定
							Ember.addObserver(data, "_checked", ctrl.bindNetworkCheckedToCheckbox);
							return true;
						}
					}
				},
				{
					headerText: "级别",
					dataKey:"alertSevertiyName",
					width: 60,
					allowSort: true,
					ensurePxWidth: true,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var date = args.row.data.alertSevertiyName;
							if("严重"==date){
								var cb = $("<div class='label label-important'></div>").text(date);
								cb.appendTo(args.$container);
							}
							if("警告"==date){
								var cb = $("<div class='label label-warning'></div>").text(date);
								cb.appendTo(args.$container);
							}
							if("提醒"==date){
								var cb = $("<div class='label label-info'></div>").text(date);
								cb.appendTo(args.$container);
							}
							return true;
						}
					}
				},
				{
					headerText: "告警类型",
					dataKey:"alertTypeName",
					width: 100,
					ensurePxWidth: true
				},
				{
					headerText: "开始时间",
					dataKey:"firstTime",
					width: 130,
					allowSort: true,
					ensurePxWidth: true,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var date = new Date(args.row.data.firstTime);
							var  dateFor=APM.util.formatDate(date, "yyyy-MM-dd H:mm");
							var cb = $("<div class='date-text'></div>").text(dateFor);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "持续时间",
					dataKey:"repeat",
					width: 80,
					allowSort: true,
					ensurePxWidth: true,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var data = args.row.data;
							var value = data.repeat;
							var hour = Math.floor(value/60);
							var minute = value%60;
							value = (hour<1?"":hour+"小时") + minute+"分钟";
							args.$container.text(value).addClass('text-l');
							return true;
						}
					}
				},
				{
					headerText: "告警来源",
					dataKey:"source",
					ensurePxWidth: true,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var data = args.row.data;
							var value = data.source;
							args.$container.attr("title",value).addClass('text-l')
								.css("cursor", "pointer");
						}
					}
				},
				{
					headerText: "描述",
					dataKey:"desc",
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var data = args.row.data;
							var value = data.desc;
							args.$container.attr("title",value).addClass('text-l');
						}
					}
				},
				{
					headerText: "状态",
					dataKey:"clearStatus",
					width: 60,
					ensurePxWidth: true,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var data = args.row.data;
							var value = data.clearStatus;

							if(value == 0) {
								args.$container.text("新告警");
							}else if(value == 1) {
								args.$container.text("已恢复");
							}
							return true;
						}
					}
				},
				{
					headerText: "处理",
					dataKey:"alertStatusName",
					width: 60,
					ensurePxWidth: true
				}
			],

			networkCheckboxClick: function(e) {
				e.stopPropagation();

				var cb = $(this);
				var model = cb.data("model");
				var checked = cb.prop("checked");

				cb.prop("checked", checked);
				Ember.set(model, "_checked", checked);
			},

			bindNetworkCheckedToCheckbox: function() {
				var data = this,
					cb = data._$checkbox;
				var checked = Ember.get(data, "_checked");
				cb.prop("checked", checked);

				// data.ctrl.clrSelectChange(data, checked);
			},

			getAlertIds : function() {
				return Ember.A(Ember.A(this.get("gridDataSource")).filterBy("_checked", true)).mapBy("id");
			},

			//列表数据存放数组
		 	gridDataSource:  Ember.A(),
		 	
		 	queryAlarm : function(){
					var ctrl = this;
					var form = ctrl.get("form");
					var sortField = ctrl.get("sortField");
					var sortBy = ctrl.get("sortBy");
					console.log(form.status);
					console.log(form.clearStatus);
					ctrl.store.ajax("GET", "alarms/alarmsData", {
						severity:form.severity,
						// firstTime : +form.firstTime,// - form.firstTime % 86400000 - 28800000 + 86400000,
						// lastTime : +form.lastTime,// - form.lastTime % 86400000+86399000 - 28800000 + 86400000,
						firstTime : +ctrl.get("startDate"),
						lastTime : +ctrl.get("endDate"),
						type : form.alarmType,
						source : form.source,
						status : form.status,
						clearStatus : form.clearStatus,
						sortField:sortField,
						sortBy:sortBy,
						pageSize: 10,
						pageIndex: 0,
						key : form.key
					}).then(function(response) {
						//todo: 保存成功逻辑
						if(response.meta){
							ctrl.set("pageIndex",response.meta.pageIndex);
							ctrl.set("pageSize",response.meta.pageSize);
							ctrl.set("totalRows",response.meta.total);
							if(response.result){
								ctrl.set('gridDataSource',response.result);
							}
						}

						// 设置当前radio按钮选中
						$("input[name='alarm-type']").each(function(index){
							index++;
							if(!ctrl.get("isAlarmMenu"+index)){
								$(this).prop("checked",true);
								return false;
							}
						})
					});
				},

			actions : {
				reset: function() {
					var ctrl=this;
					ctrl.set("saveResult", null);
					ctrl.set("isAlarmMenu1",false);
					ctrl.set("isAlarmMenu2",true);
					ctrl.set("isAlarmMenu3",true);

					//重新设置默认值
					ctrl.set('form.alarmType',null);
					ctrl.set('form.status',-1);
					ctrl.set('form.clearStatus', 0);
					ctrl.set('form.severity',50);
					ctrl.set('form.source',null);
					ctrl.set('form.key',null);
					ctrl.set('form.firstTime',new Date(new Date(new Date() - timeD_value)-1000*60*60*24*7));
					ctrl.set('form.lastTime',new Date(new Date() - timeD_value));
					ctrl.set("pageIndex", 0);
				},

				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);
					this.requireAlarmsData();
				},

				gridCellClicked: function(e, args, view){
					var row = args.cell.row();
					var column = args.cell.column();
					var data = row.data;
					var timer = data.firstTime - 60000 + data.thresholdTime*60000;
					if ( row && (row.type & $.wijmo.wijgrid.rowType.data) ) {
						if(column.dataKey == "source"){
							if(data.applicationId == "default"){
								if(data.serviceId == null){

									this.transitionToRoute("business.detail.gauge", data.applicationId, {queryParams: {startTime: timer}});
								}else{
									window.location.href="/web/#/service/server/"+data.serviceId+"/overview";
								}
														
								return;
							}else{
								if(data.resourceId == null){
									if(data.type.indexOf("b") != -1){
										$.cookie("isThreshold", "business", '/');
									}else{
										$.cookie("isThreshold", "system", '/');
									}
									
									this.transitionToRoute("business.detail.gauge", data.applicationId, {queryParams: {startTime: timer}});
								}else{
									if(data.type.indexOf("b") != -1){
										$.cookie("isThreshold", "business", '/');
									}else{
										$.cookie("isThreshold", "system", '/');
									}
									window.location.href="/web/#/business/"+data.applicationId+"/nodetype/"+data.resourceId+"/overviewtype";
								}
							}
							
						}
					}
				},

				gridSorted:function(e, data, view){
					view.ensureControl(false);
					var sortKey= data.sortCommand;
					var	dict = {"alertSevertiyName": "severity", "alertTypeName": "type", "alertStatusName": "status"},
						sort=sortKey.substring(sortKey.lastIndexOf(' ')+1),
						dataKey = data.column.dataKey;
					this.set("sortField", dict[dataKey] || dataKey);
					this.set("sortBy",sort);
					this.requireAlarmsData()
					 .then(function(){
					 	view.ensureControl(false);
					 });
				},

				
				tabshow: function(tabIndex){
					var ctrl = this;
					ctrl.set("pageIndex", 0);
					if(tabIndex=="1"){
						ctrl.set("sortField",null);
						ctrl.set("sortBy",null);
						ctrl.set("isAlarmMenu1",false);
						ctrl.set("isAlarmMenu2",true);
						ctrl.set("isAlarmMenu3",true);
						this.set("form.severity",50);
						ctrl.requireAlarmsData();
					}
					if(tabIndex=="2"){
						ctrl.set("sortField",null);
						ctrl.set("sortBy",null);
						ctrl.set("isAlarmMenu2",false);
						ctrl.set("isAlarmMenu1",true);
						ctrl.set("isAlarmMenu3",true);
						this.set("form.severity",20);
						ctrl.requireAlarmsData();
					}
					if(tabIndex=="3"){
						ctrl.set("sortField",null);
						ctrl.set("sortBy",null);
						ctrl.set("isAlarmMenu3",false);
						ctrl.set("isAlarmMenu1",true);
						ctrl.set("isAlarmMenu2",true);
						this.set("form.severity",10);
						ctrl.requireAlarmsData();
					}
				},

				refreshAlarm : function() {
					var ctrl = this;
					ctrl.send("queryAlarmNum");
					ctrl.send("queryAlarm");
				},

				updAlarm : function() {
					var ctrl = this;
					var form = this.get("form");
					var alertArray = this.getAlertIds();

		//			var alartStr=JSON.stringify(alertArray);
					if(alertArray.length == 0){
						confirmDialog("请选择要确认的告警!");
						return false;
					}else{
						confirmDialog("确定要确认该告警吗？")
						.then(function(){

							ctrl.store.ajax("PUT", "alarms/alarms", {
								alarmIds:alertArray.join(),
		                        status: 1//确认状态
							}).then(function(response) {
								//保存成功逻辑
								if(response.status=="success"){
									alertTip("更新成功！");
									ctrl.send("queryAlarmNum");

									ctrl.queryAlarm();
								}
							}, function() {
								ctrl.set("addDisabled", false);
							});
						});
					}
				},

				clrAlarm : function() {
					var ctrl = this;
					var form = this.get("form");
					var alertArray = this.getAlertIds();

		//			var alartStr=JSON.stringify(alertArray);
					if(alertArray.length == 0){
						confirmDialog("请选择要清除的告警!");
						return false;
					}else{
						confirmDialog("确定要清除该告警吗？")
						.then(function(){
							ctrl.store.ajax("PUT", "alarms/alarms", {
								alarmIds:alertArray.join(),
		                        status: 2//清除状态
							}).then(function(response) {
								//保存成功逻辑
								if(response.status=="success"){
									alertTip("更新成功！");
									ctrl.send("queryAlarmNum");
									ctrl.queryAlarm();
								}
							}, function() {
								ctrl.set("addDisabled", false);
							});
						});
					}
				},

				delAlarm : function() {
					var ctrl = this;
					var form = this.get("form");
					var alertArray = this.getAlertIds();
					if(alertArray.length == 0){
						alert("请选择要删除的告警!");
						return false;
					}else{
						confirmDialog("确定要删除该告警吗？")
						.then(function(){
							var alartStr=JSON.stringify(alertArray).replace("[","").replace("]","");
							ctrl.store.ajax("DELETE", "alarms/alarms", {
								alarmIds:alartStr
							}).then(function(response) {
								//todo: 保存成功逻辑
								if(response.status=="success"){
									alertTip("删除成功！");
									ctrl.send("queryAlarmNum");
									ctrl.send("queryAlarm");
								}
							}, function() {
								ctrl.set("addDisabled", false);
							});
						});
					}
				},
				
				queryAlarmNum: function() {
					var ctrl = this;
					var form = ctrl.get("form");
					ctrl.store.ajax("GET", "alarms/alarmsRankNum").then(function(response) {
						//todo: 保存成功逻辑
						var rankList=response.serRankNums;
						for(var k=0;k<rankList.length;k++){
							rankObj=rankList[k];
							if(rankObj.alarmCode==50){
								if(rankObj.alarmNum>99){
									ctrl.set("form.alarmNum1","99+");
								}else{
									ctrl.set("form.alarmNum1",rankObj.alarmNum);
								}
							}
							if(rankObj.alarmCode==20){
								if(rankObj.alarmNum>99){
									ctrl.set("form.alarmNum2","99+");
								}else{
									ctrl.set("form.alarmNum2",rankObj.alarmNum);
								}
							}
							if(rankObj.alarmCode==10){
								if(rankObj.alarmNum>99){
									ctrl.set("form.alarmNum3","99+");
								}else{
									ctrl.set("form.alarmNum3",rankObj.alarmNum);
								}
							}
						}
						ctrl.set('menuLists',Ember.A(rankList));
					});
				},

				timeRangesChange: function(timeRange){
					this.set("startDate",timeRange.startDate);
					this.set("endDate",timeRange.endDate);
					//this.requireAlarmsData();
					//console.log(new Date(+timeRange.startDate) +", "+ new Date(+timeRange.endDate));
					this.queryAlarm();
				},
				
			}
		});

		APM.AlarmAlertplatformController = Controller;

		return Controller;
	}
);	